package com.keepsport.keepsportapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keepsport.keepsportapi.dao.UserPlanDao;
import com.keepsport.keepsportapi.dto.UserActivityDto;
import com.keepsport.keepsportapi.dto.UserPlanDto;
import com.keepsport.keepsportapi.entity.UserActivity;
import com.keepsport.keepsportapi.entity.UserCourse;
import com.keepsport.keepsportapi.service.intf.UserPlanService;
import com.keepsport.keepsportapi.vo.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class UserPlanImpl implements UserPlanService {
    @Resource
    private UserPlanDao dao;
    @Override
    public R save( int cid,int token) {
        QueryWrapper<UserCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",token);
        wrapper.eq("cid",cid);
        Lock lock=new ReentrantLock();
        lock.lock();//加锁
        try{
            if(dao.selectOne(wrapper)==null) {
                //8.活动 可以报名
                if (dao.insert(new UserCourse(cid,token)) > 0) {
                    //发送站内信  报名成功
                    return R.ok();
                }
            }else {
                return R.fail("亲，您已经报过名了，请勿重复报名");
            }
        }finally {
            lock.unlock();//释放锁
        }
        return R.fail();
    }


    @Override
    public R query(int token) {
        List<UserPlanDto> list=dao.selectByUid(token);
            return R.ok(list);

    }
}
